import React, { Component } from 'react';
import {
  View,
  Text,
  StyleSheet,
  DeviceEventEmitter,
  FlatList,
} from 'react-native';
import produce from 'immer';
import { PollingItem } from '../../components/polling';
import Theme from '../../native-base-theme/variables/commonColor';
import * as request from '../../services/pollingRequest';
import ZlstIcon from '../../components/zlst-icons';
import {
  BlankBackground, ListFooter, Loading,
} from '../../components';

const fontColor = '#ffffff';

class PollingRecord extends Component {

  page = 1; // 分页请求的当前页数

  startPosition = 0; // 开始滑动的位置

  index = 0; // 记录当前page的index

  static navigationOptions = {
    header: null,
  }

  initListhener = null;

  constructor(props) {
    super(props);
    this.state = {
      records: [],
      currentData: {},
      refreshing: false,
      isMore: false,
      isError: false,
      showLoading: true,
    };
  }

  componentDidMount() {
    if (
      this.props.navigation
      && this.props.navigation.state
      && this.props.navigation.state.params
    ) {
      this._fetchData(this.props.navigation.state.params.data);
    } else {
      this.initListhener = DeviceEventEmitter.addListener('swipeToInpectionDetail', this._fetchData);
    }
  }

  componentWillUnmount() {
    if (this.initListhener) {
      this.initListhener.remove();
      this.initListhener = null;
    }
  }

  fetchList = async (payload) => {
    try {
      this.setState({ isError: false });
      const currPage = this.page + 1;
      const { data, pageNum, totalNum } = await request.checkRecord({ ...payload, page: currPage, rows: 10 });
      this.setState(produce(draft => {
        // eslint-disable-next-line no-restricted-syntax
        draft.records.push(...data);
        this.page = pageNum;
        draft.isMore = draft.records.length < totalNum;
        draft.total = totalNum;
      }));
    } catch (error) {
      this.setState({ isError: true });
    }
  }

  refreshList = async (payload) => {
    try {
      this.setState({ isError: false });
      const { data, pageNum, totalNum } = await request.checkRecord({ ...payload, page: 1, rows: 10 });
      const isMore = data.length < totalNum;
      this.setState(produce(draft => {
        // eslint-disable-next-line no-restricted-syntax
        draft.records = data;
        draft.refreshing = false;
        this.page = pageNum;
        draft.isMore = isMore;
        draft.total = totalNum;
      }));
    } catch (error) {
      this.setState({ isError: true, refreshing: false });
    }
  }

  initRefreshList = async (payload) => {
    try {
      this.setState({ showLoading: true, isError: false, records: [] });
      const { data, pageNum, totalNum } = await request.checkRecord({ ...payload, page: 1, rows: 10 });
      const isMore = data.length < totalNum;
      this.setState(produce(draft => {
        draft.records = data;
        draft.showLoading = false;
        this.page = pageNum;
        draft.isMore = isMore;
        draft.total = totalNum;
      }));
    } catch (error) {
      this.setState({ isError: true, showLoading: false });
    }
  }

  // 刷新时候获取数据
  _onRefresh = () => {
    this.refreshList({ condition: '', equipmentCode: this.state.currentData.equipmentCode });
  }

  // 初始化的时候获取数据
  _onInitRefresh = () => {
    this.initRefreshList({ condition: '', equipmentCode: this.state.currentData.equipmentCode });
  }

  // 上拉加载数据
  _onEndReached = () => {
    if (this.state.isMore) {
      this.fetchList({ condition: '', equipmentCode: this.state.currentData.equipmentCode });
    }
  }

  // 列表上拉加载的组件
  _renderListFooter = () => (
    (this.state.records.length > 0) && <ListFooter isMore={this.state.isMore} />
  );

  _fetchData = async (currentData) => {
    console.log('coming...');
    // try {
    //   this.state.records = [];
    //   console.log('data from swipe', currentData);
    //   this.setState({
    //     currentData,
    //   });
    //   DeviceEventEmitter.emit('showLoading', true);
    //   // const { equCode } = this.props.navigation.state.params;
    //   const qeury = {
    //     equipmentCode: currentData.equipmentCode,
    //     // equipmentCode: 'RX_300CKJ&924',
    //     condition: '',
    //   };
    //   const resp = await request.checkRecord(qeury);
    //   console.log('polling resp:', resp);
    //   if (resp.data && resp.data.length) {
    //     this.setState(preSatus => ({
    //       records: preSatus.records.concat(resp.data),
    //     }));
    //   }
    //   DeviceEventEmitter.emit('showLoading', false);
    // } catch (error) {
    //   console.log('fetch polling record error');
    // }
    this.setState({ currentData }, () => this._onInitRefresh());
  }

  _toMianPage = () => {
    if (this.props.navigation
      && this.props.navigation.state) {
      this.props.navigation.goBack();
    } else {
      DeviceEventEmitter.emit('swiperInfoPageEvent', -1);
    }
  }

  _itemClick = (data) => {
    console.log('itemClick , to detaipage', data);
    global.navigation.navigate({
      routeName: 'TaskDeviceDetail',
      params: {
        equipcheckId: data.item.equipcheckId,
        equipmentCode: data.item.equipmentCode,
        equipmentName: data.item.equipmentName,
      },
    });
  }

  _getListContent = () => {
    // const { records } = this.state;
    // if (records && !records.length) {
    //   return (
    //     <View>
    //       <Text
    //         style={{
    //           color: fontColor,
    //           fontSize: 16,
    //           textAlign: 'center',
    //         }}
    //       >
    //         该设备暂无巡检历史记录
    //       </Text>
    //     </View>
    //   );
    // }
    // return (
    //   <FlatList
    //     data={records}
    //     renderItem={item => <PollingItem data={item} onClick={this._itemClick} />}
    //     keyExtractor={(item, index) => item + index}
    //     onRefresh={this._onRefresh}
    //     refreshing={refreshing}
    //     onEndReachedThreshold={0.05}
    //     onEndReached={this._onEndReached}
    //     ListFooterComponent={this._renderListFooter}
    //     ItemSeparatorComponent={this._renderItemSeparator}
    //   />
    // );

    const {
      showLoading, isError, records, refreshing,
    } = this.state;

    let mView = <Loading />;
    if (!showLoading) {
      if (records.length === 0) {
        mView = <BlankBackground isError={isError} onRefresh={this._onInitRefresh} />;
      } else {
        mView = (
          <FlatList
            data={records}
            renderItem={item => <PollingItem data={item} onClick={this._itemClick} />}
            keyExtractor={(item, index) => item + index}
            onRefresh={this._onRefresh}
            refreshing={refreshing}
            onEndReachedThreshold={0.05}
            onEndReached={this._onEndReached}
            ListFooterComponent={this._renderListFooter}
            ItemSeparatorComponent={this._renderItemSeparator}
          />
        );
      }
    }

    return mView;
  }

  render() {
    return (
      <View style={styles.contianer}>
        <View style={styles.headerContent}>
          <ZlstIcon
            onPress={this._toMianPage}
            name="fanhui"
            size={24}
            color="white"
          />
          <Text style={{ color: fontColor, fontSize: 18, fontWeight: 'bold' }}>
            设备点巡检记录
          </Text>
          <View style={styles.titleOtherInfo} />
        </View>
        <View style={styles.title}>
          <Text style={[styles.fontColor, { color: '#000000' }]}>
            <Text style={[styles.fontColor, { color: '#000000' }]}>
              {this.state.currentData.equipmentName}
            </Text>
            巡检历史
          </Text>
        </View>
        <View style={styles.recordListContent}>
          {this._getListContent()}
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  contianer: {
    flex: 1,
    width: '100%',
    height: '100%',
    backgroundColor: Theme.myPrimary,
    paddingLeft: 10,
    paddingRight: 10,
  },
  fontColor: {
    lineHeight: 24,
  },
  headerContent: {
    display: 'flex',
    flexDirection: 'row',
    height: 40,
    justifyContent: 'space-between',
    alignItems: 'center',
    backgroundColor: Theme.myPrimary,
    marginBottom: 8,
  },
  titleOtherInfo: {
    width: 24,
    height: 24,
  },
  title: {
    backgroundColor: '#ffffff',
    borderLeftWidth: 8,
    borderLeftColor: '#4f6fe3',
    borderStyle: 'solid',
    padding: 10,
    fontSize: 17,
    fontFamily: 'PingFangHK-Regular',
  },
  recordListContent: {
    flex: 1,
    marginTop: 5,
  },
});

export default PollingRecord;
